/* $Id: RegisterDialogBox.java 138 2011-09-01 17:51:37Z altdotua@gmail.com $ */

package alt.djudge.frontend.client.ui;

import alt.djudge.frontend.client.ui.contest.Layout;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;


public class RegisterDialogBox extends DialogBox
{
	interface MyUiBinder extends UiBinder<Widget, RegisterDialogBox> {}

	private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

	@UiField
	TextBox txtUsername;
	
	@UiField
	PasswordTextBox txtPassword;
	
	@UiField
	PasswordTextBox txtPassword2;
	
	@UiField
	TextBox txtEmail;
	
	@UiField
	Button btnCancel;
	
	@UiField
	Button btnRegister;
	
	@UiField
	Label lblError;
	
	public RegisterDialogBox()
	{
		setWidget(uiBinder.createAndBindUi(this));
		setTitle("Login");
		
		btnCancel.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				hide();
				History.back();
			}
		});
		
		btnRegister.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				if (txtUsername.getText().length() == 0)
				{
					lblError.setText("Username must be non-empty");
					return;
				}
				if (txtPassword.getText().length() == 0)
				{
					lblError.setText("Password must be non-empty");
					return;
				}
				if (!txtPassword.getText().equals(txtPassword2.getText()))
				{
					lblError.setText("Passwords dont match");
					return;
				}
				if (!txtEmail.getText().matches("^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[a-zA-Z]{2,4}$"))
				{
					lblError.setText("Enter valid email address");
					return;
				}
				lblError.setText("");
				AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>()
				{
					@Override
					public void onSuccess(Boolean result)
					{
						if (result)
						{
    						hide();
    						History.back();
						}
						else
						{
							lblError.setText("Error. Username if already taken");
						}
					}
					
					@Override
					public void onFailure(Throwable caught)
					{
						lblError.setText("Server error. Please, try again later");
					}
				};
				
				Layout.loginService.doRegister(txtUsername.getText(), txtPassword.getText(), txtEmail.getText(), callback);
			}
		});
	};	
}
